package util;


import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.stream.XMLStreamException;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;

/**
 */
public class XmlBaseOpeaterImp{
	private StAXOMBuilder builder;
	private List<String> list = new ArrayList<String>();
	private StringBuffer content = new StringBuffer();
	private List<String> Content= new ArrayList<String>();

	public String getValueByName(String eleName) {
		getFirstElementValue(builder.getDocumentElement(), eleName);
		if (list.size() == 0) {
			return null;
		} else {
			return list.get(0);
		}
	}

	public boolean checkEleVlaue(String eleName, Object value) {
		return getValueByName(eleName).equals((String) value);
	}

	public String getEleContain(String eleName) {
		getContent(builder.getDocumentElement(), eleName);
		return content.toString();
	}

	@SuppressWarnings("unchecked")
	private void getFirstElementValue(OMElement element, String name) {
        //遍历element下的所有子元素
		StringBuffer key=new StringBuffer();
		key.append(element.getLocalName());
		for (Iterator iter = element.getChildElements(); iter.hasNext();) {
			OMElement child = (OMElement) iter.next();
			//子元素是否还有子元素
			key.append(","+child.getLocalName());
			System.out.println(key.toString());
			//key.delete(0, key.length());
			boolean isHavaChild = child.getChildElements().hasNext();
			if (child.getLocalName().equals(name)) {
				if (child.getLocalName().equals(name)) {
					if (isHavaChild) {
						list.add(null);
					} else {
						list.add(child.getText());
					}
				}
			} else {
				getFirstElementValue(child, name);
			}
		}
	}

	@SuppressWarnings("unchecked")
	private void getContent(OMElement element, String name) {
		if (!element.getLocalName().equals(name))
			for (Iterator iter = element.getChildElements(); iter.hasNext();) {
				OMElement child = (OMElement) iter.next();
				if (child.getLocalName().equals(name)) {
					content.append(child.toString());
				} else {
					getContent(child, name);
				}
			}
		else {
			content.append(element.toString());
		}
	}
	
	
//插入
	public void buildXml(InputStream in) {
		try {
			builder = new StAXOMBuilder(in);
		} catch (XMLStreamException e) {
			e.printStackTrace();
		}
	}

	public void buildXml(String xmlDate) {
		try {
			InputStream inputString = new ByteArrayInputStream(xmlDate
					.getBytes());
			builder = new StAXOMBuilder(inputString);
		} catch (XMLStreamException e) {
			e.printStackTrace();
		}
	}

	public void buildXml(File xmlFile) {
		try {
			InputStream fileInputStream = new FileInputStream(xmlFile);
			buildXml(fileInputStream);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}


}
